package com.viettel.pon.main;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.viettel.pon.R;
import com.viettel.pon.adapter.TabsPagerAdapter;
import com.viettel.pon.common.CheckConnect;
import com.viettel.pon.common.DataBaseHelper;
import com.viettel.pon.common.GlobalClass;
import com.viettel.pon.common.RequestMethod;
import com.viettel.pon.common.RestClient;
import com.viettel.pon.config.Config;

@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener {
	private Logger mLog;

	private ViewPager viewPager;
	private TabsPagerAdapter mAdapter;
	public ActionBar actionBar;
	Button btnAddTractList;
	Button btnInsertTrack;
	Button btnCancelTrack;
	EditText edtTrackName;
	EditText edtTrackDescription;
	String TabSearch;
	//String TabTrack;
	String TabView;
	String tabRreport;
	DataBaseHelper db;
	GlobalClass _glb;
	Boolean isConnectionExist = false;
    //Đối tượng kiểm tra kết nối internet
    CheckConnect _checkConnect;
	private ProgressDialog pDialog;

	public String getTabSearch() {
		return TabSearch;
	}

	public void setTabSearch(String tabSearch) {
		TabSearch = tabSearch;
	}

	public String getTabView() {
		return TabView;
	}

	public void setTabView(String tabView) {
		TabView = tabView;
	}

//	public String getTabTrack() {
//		return TabTrack;
//	}
//
//	public void setTabTrack(String tabTrack) {
//		TabTrack = tabTrack;
//	}
	

	public String getTabRreport() {
		return tabRreport;
	}

	public void setTabRreport(String tabRreport) {
		this.tabRreport = tabRreport;
	}


	// Tab titles
	private int[] tabs = { R.drawable.add,// R.drawable.vtmap_direction_headon,
			R.drawable.search,  R.drawable.report_icon, R.drawable.sync_icon, R.drawable.icon_download };
	private String[] tabsLabel = { "", "", "", "", ""};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mLog = Logger.getLogger("MainActivity");
		setContentView(R.layout.activity_main);
		db = new DataBaseHelper(getApplicationContext());

		mLog.info("khoi tao form");
		// Initilization
		viewPager = (ViewPager) findViewById(R.id.pager);
		actionBar = getActionBar();
		mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
		_checkConnect=new CheckConnect(getApplicationContext());
		_glb = (GlobalClass) getApplicationContext();
		viewPager.setAdapter(mAdapter);
		// actionBar.setHomeButtonEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		isConnectionExist=_checkConnect.checkData();
		if(isConnectionExist){
			 String URL = Config.URL_WS+"sync/checkVersion";
      	   	new LongOperation().execute(URL);
		}
		// Adding Tabs
		int len=tabs.length-1;
		mLog.info("Version = "+GlobalClass.trueVersion);
		if(!GlobalClass.trueVersion){
			len=tabs.length;
		}
		
//		for(int i=0;i<len;i++){
//			actionBar.addTab(actionBar.newTab().setIcon(tabs[i])
//					.setTabListener(this));
//		}

		actionBar.setBackgroundDrawable(new ColorDrawable(Color
				.parseColor("#3996BE")));
		
		// TODO: uncomment this line
		
		// actionBar.setCustomView(R.style.ActionBarTabStyle_Actionbarstyle);
		
		
		// Adding Tabs
		for (int i = 0; i < tabs.length; i++) {
			// for (int tab_name : tabs) {
			int tab_name = tabs[i];
			CharSequence cs = tabsLabel[i];
			Tab tab = actionBar.newTab().setIcon(tab_name)
					.setTabListener(this).setText(cs);       
		    
		    actionBar.addTab(tab);
			
		}

		/**
		 * on swiping the viewpager make respective tab selected
		 * */
		viewPager.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				return false;
			}
		});

		viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				// on changing the page
				// make respected tab selected
				// Toast.makeText(getApplicationContext(),
				// String.valueOf(pointCount), Toast.LENGTH_SHORT).show();
				// Toast.makeText(getApplicationContext(),
				// String.valueOf(position), Toast.LENGTH_SHORT).show();
				// viewPager.getCurrentItem();
				// if(viewPager.getCurrentItem()==0 && pointCount==2){
				actionBar.setSelectedNavigationItem(position);
				// }else if(viewPager.getCurrentItem()!=0 && pointCount>0){
				// actionBar.setSelectedNavigationItem(position);
				// }
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		// on tab selected
		// show respected fragment view
		viewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
	}
	
	

	
	
    public String getRespose(String url) {
		String response = "";
		try{
			
			RestClient client = new RestClient(url);
			try {
			    client.Execute(RequestMethod.POST);
			} catch (Exception e) {
			    e.printStackTrace();
			  
			}
			response = client.getResponse();
			
		}catch(Exception e){
			
			System.out.println(e.getMessage());
		}
	    return response;
	}
	

	 // Class with extends AsyncTask class
    
    private class LongOperation  extends AsyncTask<String, Void, Void> {
          
        // Required initialization
         
        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        @Override
		protected void onPreExecute() {
            // NOTE: You can call UI Element here.
              
            //Start Progress Dialog (Message)
        	pDialog = new ProgressDialog(MainActivity.this);
        	pDialog.setMessage("Checking version..");
        	pDialog.show();
             
             
        }
        
        // Call after onPreExecute method
        @Override
		protected Void doInBackground(String... urls) {
                try
                {  
                  // Send POST data request
                   Content= getRespose(urls[0]);
                }
                catch(Exception ex)
                {
                    Error = ex.getMessage();
                }
                finally
                {
                }
             
            /*****************************************************/
            return null;
        }
          
        @Override
		protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.
              
            // Close progress dialog
        	pDialog.dismiss();
              
            if (Error != null) {
            	  Toast.makeText(getBaseContext(), Error, Toast.LENGTH_LONG).show();
                  
            } else {    
                JSONObject jsonResponse;
                try {
                       if(Content.equals("")|| Content==null || Content.equals("-1")){
                    	   AlertDialog myErrorDialog = createDialogError("Lỗi kết nối tới server!");
                    	   myErrorDialog.show();
                       }else{
                     /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                     jsonResponse = new JSONObject(Content);
                        	/*
                        	 * get version tren server
                        	 */
                        	String versionCode=jsonResponse.has("versionCode")!=true ?"":jsonResponse.getString("versionCode");
                        	String pathFile=jsonResponse.has("pathFile")!=true ?"":jsonResponse.getString("pathFile");
                        	PackageInfo pInfo = null;
							pInfo = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
							String versionName = "-1";
							if (pInfo != null)
								versionName = pInfo.versionName;
							/*
							 * Check version tren server voi version client
							 */
							if (!versionCode.equals("") && !versionName.equalsIgnoreCase(versionCode)) {
								GlobalClass.trueVersion=false;
								GlobalClass.versionCode=versionCode;
	            				GlobalClass.pathFile=pathFile;
								createDialogError("Phần mềm đang có phiên bản mới, vui lòng cập nhật phiển bản mới để tránh phát sinh lỗi").show();
							}
                       }
                 } catch (Exception e) {
           
                     e.printStackTrace();
                 }
   
                  
             }
        }
          
    }
    private AlertDialog createDialogError(String msg){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Thông báo");
        builder.setMessage(msg);
        builder.setCancelable(false);
        //Táº¡o nÃºt ok
        builder.setNegativeButton("Ok",
                new DialogInterface.OnClickListener() {
                    @Override
					public void onClick(DialogInterface dialog,
                            int which) {

                    }
                });
        AlertDialog dialog = builder.create();
        return dialog;
    }
	

}
